# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
from optparse import OptionParser

from cve_ease import activate_session, purge_db
from cve_ease.helper import one_instance_check
from cve_ease.models import CVE, SA, CVELOG, SALOG

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_db(gconfig, db_session, args):
    """[basic] Persistant database manage tool"""

    # one instance
    lock = one_instance_check(gconfig.LOCK_FILE_PATH)
    if lock:
        raise Exception(f"Another cve-ease already running")
    usage = "usage: %prog db <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-p', '--purge', dest='purge', action='store_true', default=False,
                      help='purge db and recreate it (Danger Operation)')
    parser.add_option('-s', '--stats', dest='stats', action='store_true', default=False,
                      help='get database statistics')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    if gconfig.debug:
        print(" * active sql session")

    if options.purge:
        print("Danger! This operations is very dangerous!")
        user_input = input("Please make sure three times, if you still want to purge db, press 'yes' : ")
        print()
        if user_input == 'yes':
            try:
                purge_db(db_session)
            except Exception as e:
                print("Purge/Recreate database failed! ", str(e))
                exit(1)
            print("Purge/Recreate database done!")
        else:
            print("skip without purge, bye~")
    elif options.stats:
        print("database file ", gconfig.DB_FILE_PATH)
        cve_count = session.query(CVE).count()
        print("CVE record num:", cve_count)
        sa_count = session.query(SA).count()
        print("SA record num:", sa_count)
        cvelog_count = session.query(CVELOG).count()
        print("CVELOG record num:", cvelog_count)
        sa_count = session.query(SALOG).count()
        print("SALOG record num:", sa_count)
    else:
        parser.print_help()
